<?php

namespace core\system;

class Session {

    private $meta = '__meta';

    public function __get($name) {
        $this->start();
        $val = $this->get($name);
        return $val != null ? json_decode($val) : $val;
    }

    public function __set($name, $value) {
        $_SESSION[$name] = ($value != null) ? json_encode($value) : $value;
    }

    public function __construct() {
        $this->start();
    }

    public function start() {
        if (!isset($_SESSION)) {
            session_start();
            (isset($_SESSION[$this->meta]) || $this->init()) || $_SESSION[$this->meta]['activity'] = $_SERVER['REQUEST_TIME'];
        }
    }

    /**
     * write session data to store and close the session.
     */
    public function commit() {
        session_commit();
    }

    public function destroy() {
        $_SESSION = array();
        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]
            );
        }
        session_destroy();
    }

    public function get($name, $default = NULL) {
        return isset($_SESSION[$name]) ? $_SESSION[$name] : $default;
    }

    /**
     * @return string
     */
    public function getName() {
        return session_name();
    }

    private function init() {
        $_SESSION[$this->meta] = array(
            'ip' => $_SERVER['REMOTE_ADDR'],
            'name' => session_name(),
            'created' => $_SERVER['REQUEST_TIME'],
            'activity' => $_SERVER['REQUEST_TIME'],
        );
        return true;
    }

}
